import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:wanxiang_app/bean/pay_list_entity.dart';
import 'package:wanxiang_app/pages/my/logs.dart';
import 'package:wanxiang_app/pages/my/topUp.dart';
import 'package:wanxiang_app/pages/my/withdraw.dart';
import 'package:wanxiang_app/utils/common.dart';
import 'package:wanxiang_app/utils/constant.dart';
import 'package:wanxiang_app/utils/user_util.dart';
import '../../bean/login_entity.dart';
import '../../utils/network_manager.dart';
import '../../utils/network_url.dart';
import '../../utils/toast_util.dart';
import '../../widgets/myappbar.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:easy_refresh/easy_refresh.dart';

import 'bindAccount.dart';
import 'charge.dart';


class WalletController extends GetxController{

  @override
  void onInit() {
    super.onInit();
    _getService();
    _getInfo();
  }
  @override
  void onClose() {
    super.onClose();
  }
  List<PayListData> list = [];
  void _getService(){
    DioManager.getInstance().post(ServiceUrl.payList,{
      "user_name": UserUtil.getUSER()?.userName
    }, (data) async {
      PayListEntity bannerEntity = PayListEntity.fromJson(jsonDecode(data));
      list = bannerEntity.data;
      update();
    }, (error) {
      ToastUtil.show(error);
    });
  }
  String amount = "";
  _getInfo() {
    DioManager.getInstance().post(ServiceUrl.myInfo,{
      "user_name":UserUtil.getUSER()?.userName
    }, (data1) async {
      LoginEntity  entity = LoginEntity.fromJson(jsonDecode(data1));
      // UserUtil.saveUSER(entity.data);
      var map = jsonDecode(data1);
      var map2 = map['data'];
      amount=map2['amount'].toString();
      print('amount==='+amount);
      UserUtil.saveUSER2(jsonEncode(map2).toString());
      update();

    }, (error) {
      ToastUtil.show(error);
    });
  }

  EasyRefreshController easyRefreshController = EasyRefreshController(
    controlFinishRefresh: true,
    controlFinishLoad: true,
  );
}


class WalletPage  extends   GetView<WalletController>  {

  late WalletController controller ;
  late BuildContext context ;
  @override
  Widget build(BuildContext context1) {
    Get.lazyPut<WalletController>(() => WalletController());
    controller = Get.find();
    context = context1;

    return GetBuilder<WalletController>(
      builder: (_){
        return  Scaffold(
            appBar: MyAppBar(context: context, title: '钱包',hasLeading: true,),
            backgroundColor: Colors.white,
            body:_content());
      },
    );
  }


  Widget _empty(){
    return Container(
      alignment: Alignment.center,
      child: Image.asset(Constant.IMG_BASE+'empty.png',width: 150.w,height: 127.h,),
    );
  }

  Widget _content(){
    return Container(
      padding: EdgeInsets.fromLTRB(16.w, 16.h, 16.w, 0),
      child: Column(
        children: [
          _top(),
          SizedBox(height: 20.h,),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              _part(Constant.IMG_BASE+'wallet_in.png','充值'),
              _part(Constant.IMG_BASE+'wallet_out.png','提现'),
              _part(Constant.IMG_BASE+'wallet_log_in.png','充值记录'),
              _part(Constant.IMG_BASE+'wallet_log_out.png','提现记录'),
            ],
          ),
          SizedBox(height: 27.h,),
          Row(
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              Text('余额明细',style: TextStyle(
                  color: Color(0xFF333333),
                  fontSize: 15.sp
              ),),
            ],
          ),
          SizedBox(height: 14.h,),
          controller.list.length==0?_empty():
          Container(
              height: MediaQuery.of(context).size.height - 376.h,
              child:   _refresh()
          ),
        ],
      ),
    );
  }

  Widget _refresh(){
    return Scaffold(
      backgroundColor: Colors.white,
        body:  EasyRefresh(
          header: ClassicHeader(
            dragText: 'Pull to refresh'.tr,
            armedText: 'Release ready'.tr,
            readyText: 'Refreshing...'.tr,
            processingText: 'Refreshing...'.tr,
            processedText: 'Succeeded'.tr,
            noMoreText: 'No more'.tr,
            failedText: 'Failed'.tr,
            messageText: 'Last updated at %T'.tr,
          ),
          footer: ClassicFooter(
            dragText: 'Pull to load'.tr,
            armedText: 'Release ready'.tr,
            readyText: 'Loading...'.tr,
            processingText: 'Loading...'.tr,
            processedText: 'Succeeded'.tr,
            noMoreText: 'No more'.tr,
            failedText: 'Failed'.tr,
            messageText: 'Last updated at %T'.tr,
          ),
          controller:   controller.easyRefreshController,
          onRefresh: () async {
            controller.easyRefreshController.finishRefresh();
            controller._getService();
          },
          onLoad: () async {
            controller.easyRefreshController.finishLoad(
                IndicatorResult.noMore );
            controller._getService();
          },
          child: ListView.builder(
            itemBuilder: (context, index) {
              return _item(controller.list[index]);
            },
            itemCount: controller.list.length,
          ),
        )
    );
  }

  Widget _item(PayListData item){
    return Container(
      margin: EdgeInsets.only(top: 6.h),
      width: MediaQuery.of(context).size.width - 32.w,
      padding: EdgeInsets.only(left: 16.w,right: 16.w),
      height: 76.h,
      decoration: BoxDecoration(
        color: Colors.white,
          borderRadius: BorderRadius.circular(10.r),
        border: Border.all(color: Color(0x0D000000),width: 1.w)
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              Text('订单编号：',style: TextStyle(
                  color: Color(0xFF333333),
                  fontSize: 14.sp
              ),),
              Text(item.id.toString(),style: TextStyle(
                  color: Color(0xFF999999),
                  fontSize: 13.sp
              ),),
            ],
          ),

          SizedBox(height: 7.h,),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(item.way,style: TextStyle(
                color: Color(0xFF333333),
                fontSize: 14.sp
              ),),
              Text(Common.patStatusToText(item.status),style: TextStyle(
                  color: Color(0xFF999999),
                  fontSize: 13.sp
              ),),
            ],
          ),
          SizedBox(height: 7.h,),

          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(item.time,style: TextStyle(
                  color: Color(0xFF999999),
                  fontSize: 13.sp
              ),),
              item.way.contains(RegExp('支付'), 0)?
              Text('-'+item.amount.toString(),style: TextStyle(
                  color: Color(0xff00DB2C),
                  fontWeight: FontWeight.bold,
                  fontSize: 15.sp
              ),):
              Text('+'+item.amount.toString(),style: TextStyle(
                  color: Color(0xFFF43F50),
                  fontWeight: FontWeight.bold,
                  fontSize: 15.sp
              ),),
            ],
          ),

        ],
      ),
    );
  }
  
  Widget _part(img,name){
    return InkWell(
      onTap: (){
        if(name == '充值'){
          Get.to(()=>TopUpPage(),arguments: {
          },preventDuplicates:false)?.then((value) => {
            controller._getInfo()
          });
        }else if(name == '提现'){
          // ToastUtil.show('暂未开通此功能');
          Get.to(()=>WithdrawPage(),preventDuplicates:false)?.then((value) => {
            controller._getInfo()
          });
        }else {
          Get.to(()=>LogsPage(),arguments: name,preventDuplicates:false);
        }

      },
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Image.asset(img,width: 61.w,height: 61.h,),
          SizedBox(height: 9.h,),
          Text(name,style: TextStyle(
              color: Color(0xFF333333),
              fontSize: 13.sp
          ),)
        ],
      )
    ) ;
  }

  Widget _top(){
    return Container(
      width: MediaQuery.of(context).size.width - 32.w,
      height: 116.h,
      padding: EdgeInsets.only(left: 35.w,right: 35.w),
      decoration:  BoxDecoration(
        borderRadius: BorderRadius.circular(20.r),
          gradient: const LinearGradient(      //渐变位置
              begin: Alignment.centerLeft, //右上
              end: Alignment.centerRight, //左下
              //渐变颜色[始点颜色, 结束颜色]
              colors: [Color(0xFF7B86FE), Color(0xFF4B69FF),Color(0xFF7B91FE)]
          )
      ),

      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text('钱包余额',style: TextStyle(color: Colors.white,fontSize: 14.sp)),
              SizedBox(height: 12.h,),
              Text(controller.amount.toString(),style: TextStyle(color: Colors.white,fontSize: 26.sp,fontWeight: FontWeight.bold)),
            ],
          ),
          InkWell(
            onTap: (){
              Get.to(()=>BindAccountPage(),arguments: {
              },preventDuplicates:false);
            },
            child:     Container(
              alignment: Alignment.center,
              width: 88.w,
              height: 32.h,
              decoration: BoxDecoration(
                  color: Color(0xFFD2DAFF),
                  borderRadius: BorderRadius.circular(16.r)
              ),
              child: Text('账号设置',style: TextStyle(
                  color:Color(0xFF007BE5) ,
                  fontSize: 12.sp
              ),),
            )
          )

        ],
      ) ,
    );
  }

}